package web.get;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.Book;
import domain.User;
import service.BookService;
import service.UserService;
import service.impl.BookServiceImpl;
import service.impl.UserServiceImpl;
import util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取所有公共的书籍，
 * 无须验证登录信息
 */
@WebServlet("/getCommonBook")
public class GetCommonBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String,Object> msg = new HashMap<>(8);
        try{
            //获取公共书籍，（上传者uid为0）
            BookService bs = new BookServiceImpl();
            List<Book> commonBook = bs.getCommonBook();
            //传输
            msg.put("msg","成功");
            msg.put("isSuccess",true);
            msg.put("commonBook",commonBook);
            new ObjectMapper().writeValue(response.getOutputStream(),msg);
        }catch (Exception e){
            e.printStackTrace();
            msg.put("isSuccess",false);
            msg.put("msg","请求错误请刷新后尝试");
            msg.put("commonBook","");
            new ObjectMapper().writeValue(response.getOutputStream(),msg);
        }
    }
}
